package com.iss.card.view.mycard;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.iss.card.R;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.IBackKeyListener;
import com.iss.card.common.Tools;
import com.iss.card.model.UnpayFormItemModel;
import com.iss.card.model.UserInfo;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.webservice.BaseModel;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.iss.card.webservice.WebServiceUtils;

public class UnpayFormFragment extends Fragment implements OnClickListener, IBackKeyListener
, OnKeyListener{

	private static final String TAG = "UnpayFormFragment";
	
	
	private Activity mContext;
	private View mainView;
	
	
	private ImageButton btnJob;
	private TextView tvName;
	private Button btnReturn;
	
	private ArrayList<UnpayFormItemModel> unpayItemList;
	private UserInfo usrInfo;
	private ViewPager itemContainer;
	private UnpayFormClickListener mListener;
	private ImageView imvNoitem;
	private void initView(){
		imvNoitem = (ImageView) mainView.findViewById(R.id.unpay_no_item);
		usrInfo = FunctionUtil.getCurrentLogInUser();
		btnJob = (ImageButton) mainView.findViewById(R.id.job_button);
		tvName = (TextView) mainView.findViewById(R.id.job_name_val);
		btnReturn = (Button) mainView.findViewById(R.id.return_button);
		itemContainer = (ViewPager) mainView.findViewById(R.id.unpay_form_item_view);
		
		getFormList();
		
		btnJob.setVisibility(View.INVISIBLE);
		btnReturn.setVisibility(View.VISIBLE);
		tvName.setText("");
		
		btnReturn.setOnClickListener(this);
		
	}
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mContext = activity;
		try {
			mListener = (UnpayFormClickListener)mContext;
		} catch (ClassCastException e) {
			Log.e(TAG, "UnpayFormClickListener ===> " + e.toString());
		}
		
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		unpayItemList = new ArrayList<UnpayFormItemModel>();
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mainView = new View(mContext).inflate(mContext, R.layout.card_unpay_form_list, null);
		
		initView();
		return mainView;
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initView();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v== btnReturn){
			mListener.onBackButtonClick();
		}
	}
	
	public void getFormList(){
		
		usrInfo = FunctionUtil.getCurrentLogInUser();
		String[] obj ={usrInfo.getUsrMobile()};

		WebServiceAsyncService asyncService = new WebServiceAsyncService();
		asyncService.setParameterToAsyncService(mContext, 
				asyncService.getNextToken(),
				Operation.OP_SERVICE_ARG_GET_NO_PAY_LIST,
				WebServiceRegistrationParameter.PARAMETERS_GET_NO_PAY_ORDER_LIST, obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_NO_PAY_ORDERLIST,
				this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		asyncService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token,Object envelope,int index) {
				if(envelope == null){
					Log.e(TAG, "envelope is null");
					return;
				}
				
				ResponseBean response = WebServiceUtils.getObjectResultToBaseInfo(envelope, UnpayFormItemModel.class);
				
				unpayItemList = (ArrayList<UnpayFormItemModel>)response.getReturnList();
				Log.d("kitexy debug", "unpayItemList  size ===> " + response.getReturnList().size());
				LayoutInflater _inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				if(unpayItemList.size() == 0){
					itemContainer.removeAllViews();
					itemContainer.setVisibility(View.GONE);
					imvNoitem.setVisibility(View.VISIBLE);
					
				}else {
					itemContainer.removeAllViews();
					itemContainer.setVisibility(View.VISIBLE);
					imvNoitem.setVisibility(View.GONE);
					itemContainer.setAdapter(new UnpayFormPageAdapter(mContext, unpayItemList));
				}
				
				
			}
		});
		
	}
	class UnpayFormPageAdapter extends PagerAdapter implements IBackKeyListener{

		private Activity mContext;
		private ArrayList<UnpayFormItemModel> mItemList;
		private LayoutInflater inflater;
		public UnpayFormPageAdapter(Activity context, ArrayList<UnpayFormItemModel> list){
			this.mContext = context;
			this.mItemList = list;
			
			inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mItemList.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(View container, int position) {
			
			final String mId = mItemList.get(position).getOrderId();
			View view = new View(mContext);
			
			view = inflater.inflate(R.layout.card_detail_unpay_form_item, null);
			viewHolder holder = new viewHolder();
			
			holder.orderAmount =(TextView) view.findViewById(R.id.unpay_form_item_order_amount);
			holder.orderDate = (TextView) view.findViewById(R.id.unpay_form_item_order_date);
			holder.orderPayer = (TextView) view.findViewById(R.id.unpay_form_item_order_payer);
			holder.consumedStoreName = (TextView)view.findViewById(R.id.unpay_form_item_custome_store);
			holder.consumeNumber = (TextView)view.findViewById(R.id.unpay_form_consume_number);
			holder.btnCancleForm = (Button) view.findViewById(R.id.unpay_form_item_btn_cancle);
			holder.BtnPayForm = (Button) view.findViewById(R.id.unpay_form_item_btn_confirm);
			holder.useCash = (TextView) view.findViewById(R.id.unpay_form_item_use_cash);
			holder.usePoints =(TextView) view.findViewById(R.id.unpay_form_item_use_point);
			holder.useValue =(TextView) view.findViewById(R.id.unpay_form_item_use_value);
			holder.discount = (TextView) view.findViewById(R.id.unpay_form_item_discount);
			
			holder.orderAmount.setText(getString(R.string.order_amount) +
					mItemList.get(position).getOrderAmount());
			holder.orderDate.setText(getString(R.string.order_date) + 
					mItemList.get(position).getOrderDate());
			holder.orderPayer.setText(getString(R.string.order_payer) +
					mItemList.get(position).getOrderPayer());
			holder.consumedStoreName.setText(getString(R.string.custome_store) +
					mItemList.get(position).getConsumedStroeName());
			holder.consumeNumber.setText(getString(R.string.consume_number) + 
					mItemList.get(position).getConsumeNumber());
			holder.useCash.setText(getString(R.string.use_cash) + 
					mItemList.get(position).getUseCash());
			holder.usePoints.setText(getString(R.string.use_point) +
					mItemList.get(position).getUsePoints());
			holder.useValue.setText(getString(R.string.use_value) +
					mItemList.get(position).getUseValue());
			holder.discount.setText(getString(R.string.discount) + 
					mItemList.get(position).getDiscount());
			
			holder.btnCancleForm.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					AlertDialog dlg = new AlertDialog.Builder(mContext).
							setTitle(mContext.getString(R.string.card_detail_remind_title))
							.setMessage(mContext.getString(R.string.card_detail_cancle_order_remind))
							.setPositiveButton(mContext.getString(R.string.card_detail_confirm_button), 
									new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									payPendingOrder(mId, ApplicationManager.UNPAY_ORDER_CANCLE);
								}
							})
							.setNegativeButton(mContext.getString(R.string.card_detail_cancle_button), 
									new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							})
							.create();
					
					dlg.show();
				}
			});
			
			holder.BtnPayForm.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog dlg = new AlertDialog.Builder(mContext).
							setTitle(mContext.getString(R.string.card_detail_remind_title))
							.setMessage(mContext.getString(R.string.card_detail_pay_order_remind))
							.setPositiveButton(mContext.getString(R.string.card_detail_confirm_button), 
									new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									finallyConfirmOrder(mId);
								}
							})
							.setNegativeButton(mContext.getString(R.string.card_detail_cancle_button),
									new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							})
							.create();
					
					dlg.show();
				}
			});
			((ViewPager)container).addView(view);
			return view;
		}
		
		class viewHolder{
			private TextView orderId, consumedStoreName, orderDate, consumeNumber, orderAmount,
			usePoints, orderPayer, discount, useValue, useCash;
			private Button btnCancleForm, BtnPayForm;
		}
		@Override  
        public void destroyItem(View arg0, int arg1, Object arg2) {  
            // TODO Auto-generated method stub  
              
        }
		
		@Override
		public void cancelUpdate(Object... params) {
			// TODO Auto-generated method stub
			
		}
	}
	
	public void payPendingOrder(String orderId, String isPay){
		
		
		String[] obj ={orderId, isPay};

		WebServiceAsyncService asyncService = new WebServiceAsyncService();
		asyncService.setParameterToAsyncService(mContext, 
				asyncService.getNextToken(),
				Operation.OP_SERVICE_ARG_PAY_PENDING_ORDER,
				WebServiceRegistrationParameter.PARAMETERS_PAY_PENDING_ORDER, obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_PAYFORMENT,
				this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		asyncService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token,Object envelope,int index) {
				if(envelope == null){
					Log.e(TAG, "envelope is null");
					return;
				}
				ResponseBean response = WebServiceUtils.getObjectResultToBaseInfo(envelope, BaseModel.class);
				if(response.getStatus() == ApplicationManager.RESPONSE_OK){
					Tools.showToast(mContext, response.getMessage());
					initView();
				}else {
					Tools.showToast(mContext, response.getMessage());
					initView();
					return;
				}
			}
		});
	}
	@Override
	public void cancelUpdate(Object... params) {
		// TODO Auto-generated method stub
		
	}

	public interface UnpayFormClickListener{
		public void onBackButtonClick();
	}
	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			mListener.onBackButtonClick();
		}
		return true;
	}
	
	private void finallyConfirmOrder(final String id){
		AlertDialog dlg = new AlertDialog.Builder(mContext).
				setTitle(getString(R.string.card_detail_remind_title))
				.setMessage(getString(R.string.card_detail_final_confirm_remind))
				.setPositiveButton(getString(R.string.card_detail_confirm_button),
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								payPendingOrder(id, ApplicationManager.UNPAY_ORDER_PAY);
								
							}
						})
				.setNegativeButton(getString(R.string.card_detail_cancle_button), 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						})
		.create();
		dlg.show();
	}
}
